/*
 * Copyright (c) 2010-2023. Axon Framework
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.axonframework.springboot.service.connection;

import org.axonframework.test.server.AxonServerContainer;
import org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory;
import org.springframework.boot.testcontainers.service.connection.ContainerConnectionSource;

/**
 * ConnectionDetailsFactory class that recognizes TestContainer instances running Axon Server. It will use the port
 * mappings generated by the test container to generate a
 * {@link org.springframework.boot.autoconfigure.service.connection.ConnectionDetails} instance that provides the
 * correct connection information.
 *
 * @author Allard Buijze
 * @since 4.9.0
 */
public class AxonServerTestContainerConnectionDetailsFactory extends ContainerConnectionDetailsFactory<AxonServerContainer, AxonServerConnectionDetails> {

    public AxonServerTestContainerConnectionDetailsFactory() {
        super(ContainerConnectionDetailsFactory.ANY_CONNECTION_NAME,
              "org.axonframework.test.server.AxonServerContainer",
              "org.axonframework.axonserver.connector.AxonServerConnectionManager");
    }

    @Override
    protected AxonServerConnectionDetails getContainerConnectionDetails(ContainerConnectionSource<AxonServerContainer> source) {
        return new AxonServerContainerConnectionDetails(source);
    }

    private static final class AxonServerContainerConnectionDetails
            extends ContainerConnectionDetails<AxonServerContainer> implements AxonServerConnectionDetails {

        AxonServerContainerConnectionDetails(ContainerConnectionSource<AxonServerContainer> source) {
            super(source);
        }

        @Override
        public String routingServers() {
            return getContainer().getAxonServerAddress() + ":" + getContainer().getGrpcPort();
        }
    }
}
